//
//  WEXComposePictureView.swift
//  microBlog
//
//  Created by apple on 16/4/26.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit
import SVProgressHUD

class WEXComposePictureView: UICollectionView {
    
    // MARK: - 定义全局属性
    
    // 通知外界调用点击方法的闭包
    var selectPictureClosure: (()->())?
    
    // 图片数组
    lazy var images: [UIImage] = []
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 初始化界面方法
    private func setupUI (){
        
        backgroundColor = UIColor.lightGrayColor()
        
        registerClass(WEXComposePictureCell.self, forCellWithReuseIdentifier: "cell")
        
        //        设置自己为自己的数据源和代理对象
        dataSource = self
        
        delegate = self
    }
    
    
    // MARK: - 设置flowlayout
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        let margin: CGFloat = 5
        let itemW = (self.frame.size.width - 2 * margin) / 3
        let itemH = itemW
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: itemW, height: itemH)
        
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
    }
    
    
    // MARK: - 提供外界调用的方法
    func addImage(image: UIImage) {
        
        if images.count < 9 {
            //            添加图片
            images.append(image)
            
            //            刷新数据
            reloadData()
            
        }else{
            
            SVProgressHUD.showErrorWithStatus("数量已经到达上限")
            
        }
    }
}

// MARK: - 数据源和代理方法
extension WEXComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        self.hidden = images.count == 0
        
        return images.count + (images.count == 0 || images.count == 9 ? 0 : 1)
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! WEXComposePictureCell
        
        //        cell.backgroundColor = UIColor.orangeColor()
        
        if indexPath.item == images.count {
            
            
            cell.image = nil
            
        }else{
            
            cell.image = images[indexPath.item]
        }
        
        cell.deleteButtonClosure = { [weak self] in
            
            self?.images.removeAtIndex(indexPath.item)
            
            self?.reloadData()
            
        }
        
        return cell
        
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.item == images.count {
            
            selectPictureClosure?()
        }
        
    }
    
}


// MARK: - 自定义cell
class WEXComposePictureCell: UICollectionViewCell {
    
    // MARK: - cell调用的属性
    
    
    // 点击按钮调用的闭包
    var deleteButtonClosure: (()->())?
    
    // 设置图片的属性
    var image: UIImage? {
        
        didSet{
            
            if image == nil{
                
                igv_imageView.image = UIImage(named: "compose_pic_add")
                
                btn_delete.hidden = true
                
            }else{
                
                btn_delete.hidden = false
                
                igv_imageView.image = image
                
                
            }
            
            
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //        添加配图
        contentView.addSubview(igv_imageView)
        
        //        添加删除按钮
        contentView.addSubview(btn_delete)
        
        //        上传图片的约束
        igv_imageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView)
            
        }
        
        
        //        删除 按钮的约束
        btn_delete.snp_makeConstraints { (make) -> Void in
            
            make.top.trailing.equalTo(contentView)
        }
        
        
        
    }
    
    
    // MARK: - 按钮点击响应事件
    @objc private func didClickDeleteBtn(button: UIButton) {
        
        deleteButtonClosure?()
    }
    
    
    
    // MARK: - 懒加载cell的子控件
    
    // 图片
    private lazy var igv_imageView: UIImageView = UIImageView()
    
    // 删除按钮
    private lazy var btn_delete: UIButton = {
        
        let deleteBtn = UIButton()
        
        deleteBtn.addTarget(self, action: "didClickDeleteBtn:", forControlEvents: UIControlEvents.TouchUpInside)
        
        deleteBtn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        
        return deleteBtn
        
    }()
    
}